<?php

namespace App\Common;

use Illuminate\Support\Str;

class Common
{
    /**
     * AES 加密
     */
    public static function AesEncode($string, $key) {
        // $data = openssl_encrypt($data, 'aes-128-ecb', base64_decode($key), OPENSSL_RAW_DATA);
        // return base64_encode($data);
        $key = substr(openssl_digest(openssl_digest($key, 'sha1', true), 'sha1', true), 0, 16);
        $data = openssl_encrypt($string, 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
        $data = strtoupper(bin2hex($data));
        return $data;
    }

    /**
     * AES 解密
     */
    public static function AesDecode($string, $key) {
        // $encrypted = base64_decode($data);
        // return openssl_decrypt($encrypted, 'aes-128-ecb', base64_decode($key), OPENSSL_RAW_DATA);

        $key = substr(openssl_digest(openssl_digest($key, 'sha1', true), 'sha1', true), 0, 16);
        $decrypted = openssl_decrypt(hex2bin($string), 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
        return $decrypted;
    }

    /**
     * 字符串转字节数组
     */
    public static function Str2Bytes($string) { 
        $bytes = array(); 
        for($i = 0; $i < strlen($string); $i++){ 
             $bytes[] = ord($string[$i]); 
        } 
        return $bytes; 
    } 

    /**
     * 获取生成批号
     */
    public static function GetBatchCode()
    {
        return date("ymd") . Str::random(4);
    }

    /**
     * 获取流水号
     */
    public static function GetSerialNumber()
    {
        return date("ymdHis") . Str::random(12);;
    }

    /**
     * 苏宁通用加密
     * base64(MD5(app_key的值+method的值+httpbody的内容+app_secret的值))】
     * 
     * @return string
     */
    public static function SuningSign(string $method, string $bodyDate, string $appKey, string $appSecret)
    {
        $content = $appKey.$method.$bodyDate.$appSecret;
        $sign = base64_encode(hex2bin(md5($content)));
        return $sign;
    }

    /**
     * 拼接suning帮客的调用地址
     * 
     * @return string 
     */
    public static function SuningUrl($url, $method, $appKey, $sign)
    {
        return sprintf("%s?method=%s&app_key=%s&sign=%s", $url, $method, $appKey, urlencode($sign));
    }
}
